﻿using AuthCenter.Api.Write.Application.Command.Role;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace AuthCenter.Api.Write.Application.Hander.Role
{
    public class DeleteUserRoleHander:IRequestHandler<DeleteUserRoleCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IBaseRepository<UserRoleModel> _userRoleRepository;
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        public DeleteUserRoleHander(IBaseRepository<RoleModel> roleRepository, IMapper mapper, IBaseRepository<UserRoleModel> userRoleRepository, IBaseRepository<UserModel> userRepository)
        {
            _roleRepository = roleRepository;
            _mapper = mapper;
            _userRoleRepository = userRoleRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 删除员工与角色的关系
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(DeleteUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var model = _userRoleRepository.GetAll().FirstOrDefault(x => x.UserId ==request. userid && x.RoleId == request.roleid && !x.IsDeleted);
            model.IsDeleted = true;
            int i=_userRoleRepository.Update(model);
            if (i > 0)
            {
                res.Code = ApiEnums.OK;
                res.Message = "删除成功";
                res.Data = i;
            }
            else 
            {
                res.Code = ApiEnums.Fail;
                res.Message = "删除失败";
            }
            return Task.FromResult(res);
        }
    }
}
